package com.jaws.zuul.filter;

import com.google.common.collect.Lists;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.http.ServletInputStreamWrapper;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StreamUtils;


import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

/**
 * 修改请求参数
 *
 * @author liangqm
 * @date 2018/3/5 9:34
 * @since v1.0.0
 */
//@Component
public class ParamFilter extends ZuulFilter {

	final private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public int filterOrder() {
		// token 校验之后执行
		return 1;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();

		// 请求路径
		Object originalRequestPath = ctx.get(FilterConstants.REQUEST_URI_KEY);
		System.out.println(originalRequestPath);
		System.out.println(request.getContextPath());
		System.out.println(request.getPathInfo());
		System.out.println(ctx.getRouteHost());

		// 请求方法
		System.out.println(request.getMethod());



		//	修改Get 请求 param
		Map<String, List<String>> params = ctx.getRequestQueryParams();
		System.out.println(params);
		params.remove("value");
		params.put("accountNo", Lists.newArrayList("newAccount!10000"));
		logger.info("params:" + ctx.getRequestQueryParams());
		//	修改Get 请求 param end


		try {
			InputStream in = (InputStream) ctx.get("requestEntity");
			if (in == null) {
				in = ctx.getRequest().getInputStream();
			}

			String body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
			System.out.println("body:" + body);

			final byte[] reqBodyBytes = body.getBytes();

			request.getParameterMap();

			//修改 post 请求 body
			ctx.setRequest(new HttpServletRequestWrapper(request) {
				@Override
				public ServletInputStream getInputStream() throws IOException {
					return new ServletInputStreamWrapper(reqBodyBytes);
				}

				@Override
				public int getContentLength() {
					return reqBodyBytes.length;
				}

				@Override
				public long getContentLengthLong() {
					return reqBodyBytes.length;
				}
			});
			//修改 post 请求 body end


		} catch (IOException e) {
			e.printStackTrace();
		}


		return null;
	}
}
